package com.cash.channel.web.mq;

import com.alibaba.fastjson.JSON;
import com.cash.channel.api.constant.Constant;
import com.cash.channel.api.model.callback.BankCardCallBack;
import com.cash.channel.web.logic.CallBackLogic;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class BindCardListener {

    @Autowired
    private CallBackLogic callBackLogic;

    @RabbitListener(containerFactory = "rabbitListenerContainerFactory", bindings = {
            @QueueBinding(
                    // 绑定queue
                    value = @Queue(value = Constant.ProConstant.CHANNEL_BANK_CARD_BIND_CALLBACK, durable = "true", autoDelete = "false"),
                    // 绑定exchange
                    exchange = @Exchange(value = "geex", durable = "true"),
                    key = Constant.ProConstant.CHANNEL_BANK_CARD_BIND_CALLBACK)})
    public void receiveCardBindCard(Channel channel, Message message) {
        try {
            // 实体接收
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
            // 字符串接收
            log.info("收到绑卡反馈通知：" + message);
            Map<String, Object> responseResult = objectMapper.readValue(message.getBody(), JSONObject.class);
            log.info("收到绑卡反馈通知 responseResult:" + JSON.toJSONString(responseResult));
            try {
                if (responseResult != null) {
                    Boolean isCustom = MapUtils.getBoolean(responseResult, "isCustom");
                    if (isCustom) {
                        BankCardCallBack bankCardCallBack = JSON.parseObject(MapUtils.getString(responseResult, "bankCardInfo"), BankCardCallBack.class);
                        callBackLogic.commonBindCardCallBack(MapUtils.getString(responseResult, "channel"), bankCardCallBack);
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw e;
            }
        } catch (Exception ex) {
            log.info("receiveCardBindCard error:");
            log.error(ex.getMessage(), ex);
        }
    }

}
